function getContextPath() {
    var pathName = document.location.pathname;
    var index = pathName.substr(1).indexOf("/");
    var result = pathName.substr(0, index + 1);
    return result;
}

function addFun(title, url, dataGridNode, newOptions) {
    var options = {
        width: 500,
        height: 300,
        title: title, href: getContextPath() + url,
        buttons: [{
            id: "addFunction",
            text: title,
            handler: function () {
                parent.$.modalDialog.openner_treeGrid = dataGridNode;
            }
        }]
    };
    $.extend(options, newOptions);
    parent.$.modalDialog(options);
}

//两级菜单
function addSubFun(title, url, dataGridNode, newOptions) {
    var options = {
        width: 500,
        height: 300,
        title: title, href: getContextPath() + url,
        buttons: [{
            id: "addFunction",
            text: title,
            handler: function () {
                parent.$.modalSubDialog.openner_treeGrid = dataGridNode;
            }
        }]
    };
    $.extend(options, newOptions);
    parent.$.modalSubDialog(options);
}

function editFun(title, url, dataGridNode, newOptions) {
    if (newOptions.id == undefined) {
        var rows = dataGridNode.datagrid('getSelections');
        newOptions.id = rows[0].id;
    } else {
        dataGridNode.datagrid('unselectAll').datagrid('uncheckAll');
    }
    var options = {
        width: 500,
        height: 300, title: title,
        href: getContextPath() + url + newOptions.id,
        buttons: [{
            id: "editFunction",
            text: '编辑',
            handler: function () {
                parent.$.modalDialog.openner_treeGrid = dataGridNode;//因为添加成功之后，需要刷新这个treeGrid，所以先预定义好
            }
        }]
    };
    $.extend(options, newOptions);
    parent.$.modalDialog(options);
}

function deleteFun(title, url, dataGridNode, newOptions) {
    var options = {width: 500, height: 300};
    $.extend(options, newOptions);
    if (options.ids == undefined) {//点击右键菜单才会触发这个
        var rows = dataGridNode.datagrid('getSelections');
        var ids=[];
        ids.push(rows[0].id);
        options.ids = ids;
    } else {//点击操作里面的删除图标会触发这个
        dataGridNode.datagrid('unselectAll').datagrid('uncheckAll');
    }
    parent.$.messager.confirm('询问', title, function (b) {
        if (b) {
            parent.$.messager.progress({
                title: '提示',
                text: '数据处理中，请稍后....'
            });
            $.post(getContextPath() + url, {
                ids: options.ids
            }, function (result) {
                parent.$.messager.progress('close');
                if (result && isSuccess(result.result)) {
                    dataGridNode.datagrid('getPager').pagination('select');
                }
                parent.$.messager.alert('提示', result.result + " " + result.message, 'info');
            }, 'JSON');
        }
    });
}

function grantFun(title, url, dataGridNode, newOptions) {
    var options = {width: 500, height: 300};
    $.extend(options, newOptions);
    if(!options.buttonId){
        options.buttonId = "grantsFunction";
    }
    if (options.id == undefined) {//点击右键菜单才会触发这个
        var rows = dataGridNode.datagrid('getSelections');
        options.id = rows[0].id;
    } else {//点击操作里面的删除图标会触发这个
        dataGridNode.datagrid('unselectAll').datagrid('uncheckAll');
    }
    parent.$.modalDialog({
        title: title,
        width: options.width,
        height: options.height,
        href: getContextPath() + url + options.id,
        data: {'id': options.id},
        buttons: [{
            id: options.buttonId,
            text: '授权',
            handler: function () {
                parent.$.modalDialog.openner_treeGrid = dataGridNode;//因为添加成功之后，需要刷新这个treeGrid，所以先预定义好
                var f = parent.$.modalDialog.handler.find('#form');
                f.submit();
            }
        }]
    });
}

//function basicAjax(url, )
//分配方法
function distributionFun(title, url, dataGridNode, newOptions) {
    var options = {width: 800, height: 500};
    $.extend(options, newOptions);
    parent.$.modalDialog({
        title: title,
        width: options.width,
        height: options.height,
        href: getContextPath() + url + options.id,
        buttons: [{
            id: "distributionFunction",
            text: title,
            handler: function () {
                parent.$.modalDialog.openner_dataGrid = dataGridNode;
                var f = parent.$.modalDialog.handler.find('#form');
                f.submit();
            }
        }]
    });
}

//供应商代码的搜索功能 no
function comboSearch(q){
    var options = $('#memberNo').combogrid("options");
    q = $('#memberNo').combo('getText');
    options.keyword = q;
    initComboDataGrid("/suppliersController/selectList.html", $("#memberNo"), options);
    $('#memberNo').combogrid("setValue", q);
}

//返回ajax获取的数据 不可使用共同的ajax TODO Ajax01
function getDetailInfo(url,id){
    var detailData;
    $.ajax({
        type: "post",
        data: {id:id},
        dataType: "json",
        async: false,
        url: getContextPath() + url,
        before: function () {
            parent.$.messager.progress({
                title: '提示',
                text: '数据处理中，请稍后....'
            });
        },
        success: function (data) {
            parent.$.messager.progress('close');
            if (data && isSuccess(data.result)) {
                detailData = data.object;
            } else {
                commonError(data.result, data.message);
            }
        },
        timeout: 1000,
        error: function (result) {
//			internalError();
            parent.$.messager.progress('close');
            templateInternalError(result.responseText);


        }
    });
    return detailData;
}

function createComboDataGrid(data, successOptions) {
    var newOptions = successOptions.newOptions;
    var comboGridNode = successOptions.comboGridNode;
    var options = {
        data: data.object,
        panelWidth: 500,
        panelHeight: 200,
        idField: 'id',
        textField: 'id',
        pagination: true,
        fitColumns: true,
        required: true,
        delay: 500,
        sortName: 'id',
        sortOrder: 'asc',
        pageSize: 5,
        pageList: [5, 10]
    }
    $.extend(options, newOptions);
    comboGridNode.combogrid(options);
}

//初始化comboGrid
function initComboDataGrid(url, comboGridNode, newOptions) {
    var type = 'get';
    if(newOptions.keyword){
        type='post';
        url = url + "?keyword = "+newOptions.keyword;
    }
    var successOptions = {
        comboGridNode:comboGridNode,
        newOptions:newOptions
    }
    postAjax(url, null, createComboDataGrid,{successArguments:successOptions,type:type,async: false});
}

function initDataGridNoPager(dataGridNode, newOptions) {
    var options = {
        fitColumns: false,
        border: false,
        pagination: false,
        width:'auto',
        height:'auto',
        idField: 'id',
        sortName: 'id',
        sortOrder: 'asc',
        checkOnSelect: true,
        singleSelect:true,
        selectOnCheck:true,
        nowrap: false,
        toolbar: '#toolbar',
        onLoadSuccess: function () {
            $('#searchForm table').show();
            parent.$.messager.progress('close');
        }
    };
    $.extend(options, newOptions);
    dataGridNode.datagrid(options);
    return dataGridNode;
}

//初始化表格
function initDataGrid(url, dataGridNode, newOptions) {
    var options = {
        fit: true,
        fitColumns: true,
        border: false,
        pagination: true,
        width:'auto',
        height:'auto',
        idField: 'id',
        sortName: 'id',
        sortOrder: 'asc',
        checkOnSelect: true,
        singleSelect:true,
        selectOnCheck:true,
        nowrap: false,
        pageSize: 10,
        pageList: [10, 20, 30, 50, 100],
        toolbar: '#toolbar',
        onLoadSuccess: function () {
            $('#searchForm table').show();
            dataGridNode.datagrid('unselectAll');
            parent.$.messager.progress('close');
        },
        onRowContextMenu: function (e, rowIndex, rowData) {
            e.preventDefault();
            $(this).datagrid('unselectAll').datagrid('uncheckAll');
            $(this).datagrid('selectRow', rowIndex);
            $('#menu').menu('show', {
                left: e.pageX,
                top: e.pageY
            });
        }
    };
    $.extend(options, newOptions);
    dataGridNode.datagrid(options);
    dataGridNode.datagrid('getPager').pagination({
        onSelectPage: function (pageNumber, pageSize) {
            newOptions.postData.rows = pageSize;
            newOptions.postData.page = pageNumber;
            newOptions.pageNumber = pageNumber;
            newOptions.pageSize = pageSize;
            initAjaxDataGrid(url, dataGridNode, newOptions)
        },
        onChangePageSize: function (pageSize) {
            newOptions.postData.rows = pageSize;
            newOptions.pageSize = pageSize;
            initAjaxDataGrid(url, dataGridNode, newOptions)
        },
        onRefresh: function () {

        }
    });
    return dataGridNode;
}
//分页表格load  TODO Ajax02
function initAjaxDataGrid(url, dataGridNode, newOptions) {
    var options = {
        postData : {
            "page": 1,
            "rows": 10
        }
    }
    $.extend(options, newOptions);
    var returnDataGrid;
    $.ajax({
        type: "post",
        data: options.postData,
        dataType: "json",
        url: getContextPath() + url,
        before: function () {
            parent.$.messager.progress({
                title: '提示',
                text: '数据处理中，请稍后....'
            });
        },
        success: function (data) {
            parent.$.messager.progress('close');
            if (data && isSuccess(data.result)) {
                options.data = data.object;
                returnDataGrid = initDataGrid(url, dataGridNode, options);
                return returnDataGrid;
            } else {
                commonError(data.result, data.message);
            }
        },
        timeout: 1000,
        error: function (result) {
//			internalError();
            templateInternalError(result.responseText);
            parent.$.messager.progress('close');

        }
    });
}

function cleanFun() {
    $('#searchForm input').val('');
    $('#searchForm select').val('');
}

function isSuccess(result) {
    return (result && result.length && result.length == 5 && result.substr(result.length - 1) === "0");
}

function isTimeOut(result) {
    return (result =="10002");
}

function internalError() {
    $.messager.alert("Error", 500 + " " + "程序内部错误", 'error');
}

function commonError(errorCode, errormsg) {
    $.messager.alert("Error", errorCode + " " + errormsg, 'error');
}

function templateInternalError(msg) {
    $('body').html(msg);
}

function createComboTree(data, successOptions){
    var options = {
        data: data.object
    }
    $.extend(options, successOptions.newOptions);
    successOptions.treeNode.combotree(options);
}

function initComboTree(url, treeNode, newOptions) {
    var successOptions ={
        treeNode:treeNode,
        newOptions:newOptions
    }
    postAjax(url, null, createComboTree,{successArguments:successOptions,type:'get'});
}

function createTree(data, successOptions){
    var options = {
        data: data.object,
        parentField: 'pid'
    };
    $.extend(options, successOptions.newOptions);
    successOptions.treeNode.tree(options);
}

function initTree(url, treeNode, newOptions) {
    var successOptions = {
        treeNode:treeNode,
        newOptions:newOptions
    }
    if (newOptions.postData) {
        postAjax(url, newOptions.postData, createTree,{successArguments:successOptions, type:'get'});
    } else {
        var options = {
            onClick: function (node) {
                if (node.attributes && node.attributes.url) {
                    var url;
                    if (node.attributes.url.indexOf('/') == 0) {/*如果url第一位字符是"/"，那么代表打开的是本地的资源*/
                        url = getContextPath() + node.attributes.url;
                    }
                } else {/*打开跨域资源*/
                    url = node.attributes.url;
                }
                addTab({
                    url: url,
                    title: node.text
                });
            }
        };
        $.extend(options, newOptions);
        successOptions.newOptions = options;
        postAjax(url, null, createTree,{successArguments:successOptions,type:'get',async: false});
    }
}

function addTab(params) {
    var iframe = '<iframe src="' + params.url + '" frameborder="0" style="border:0;width:100%;height:98%;"></iframe>';
    var t = $('#index_tabs');
    var opts = {
        title: params.title,
        closable: true,
        iconCls: params.iconCls,
        content: iframe,
        border: false,
        fit: true
    };
    if (t.tabs('exists', opts.title)) {
        t.tabs('close', opts.title);
        t.tabs('add', opts);
        parent.$.messager.progress('close');
    } else {
        t.tabs('add', opts);
    }
}

//使用list初始化input
function initSelectAjax(url, selectNode, flag){
    initSelect(selectNode, getStatusData(url), flag);
}

//获取globo status list TODO ajax03
function getStatusData(url){
    var statusData = {};
    $.ajax({
        type: "get",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        url: getContextPath() + url,
        before: function () {
            parent.$.messager.progress({
                title: '提示',
                text: '数据处理中，请稍后....'
            });
        },
        success: function (data) {
            parent.$.messager.progress('close');
            if (data && isSuccess(data.result)) {
                statusData = data.object;
            } else {
                commonError(data.result, data.message);
            }
        },
        timeout: 1000,
        error: function (result) {
//			internalError();
            templateInternalError(result.responseText);
            parent.$.messager.progress('close');
        }
    });
    return statusData;
}

function initSelect(selectNode, data, flag) {
    var str = flag ? "" : "<option value=''>请选择</option>";
    $.each(data, function (key, value) {
        str += "<option value='" + key + "' >" + value + "</option>";
    });
    selectNode.html(str);
}


function createCombobox(data, successOptions) {
    successOptions.comboboxNode.combobox({
        data: data.object,
        valueField: successOptions.key1,
        textField: successOptions.key2
    });
}

//初始化combobox
function initOptionsAjax(url, comboboxNode, key1, key2) {
    var successOptions = {
        comboboxNode: comboboxNode,
        key1: key1,
        key2: key2
    };
    postAjax(url, null, createCombobox,{successArguments:successOptions,type:'get'});
}

//获取选中table的ids  TODO ajax04
function getDataGridChecked(url, id){
    var ids = [];
    $.ajax({
        type: "post",
        dataType: "json",
        async: false,
        url: getContextPath() + url,
        data:{id:id},
        before: function () {
            parent.$.messager.progress({
                title: '提示',
                text: '数据处理中，请稍后....'
            });
        },
        success: function (data) {
            parent.$.messager.progress('close');
            if (data && isSuccess(data.result)) {
                ids = data.object;
            } else {
                commonError(data.result, data.message);
            }
        },
        timeout: 1000,
        error: function (result) {
//			internalError();
            parent.$.messager.progress('close');
            templateInternalError(result.responseText);
        }
    });
    return ids;
}

function preparLoadData(data){
    loadData(data.object);
}

function preparUserLoadData(data, successOptions){
    preparLoadData(data);

    var rowData =successOptions.deptNode.combogrid('grid').datagrid("getRows");
    $.each(rowData,function(idx,val){//遍历JSON
        if(data.object.deptNo == val.id){
            successOptions.deptNode.combogrid('grid').datagrid("selectRow", idx)
        }
    });
}

//初始化表单 部门 角色
function initLoadData(url, id) {
    postAjax(url, {'id': id}, preparLoadData,{type:'get',async: false});
}

//初始化表单 用户
function initUserLoadData(url, id,deptNode,roleNode) {
    var successOptions = {
        deptNode:deptNode
    };
    postAjax(url, {'id': id}, preparUserLoadData,{successArguments:successOptions,type:'get',async: false});
}

//自动填充表单函数
function loadData(obj) {
    var key, value, tagName, type, arr;
    for (x in obj) {
        key = x;
        value = obj[x];
        $("[name='" + key + "'],[name='" + key + "[]']").each(function () {
            tagName = $(this)[0].tagName;
            type = $(this).attr('type');
            if(tagName=='INPUT'){
                if(type=='radio'){
                    $(this).attr('checked',$(this).val()==value);
                }else if(type=='checkbox'){
                    //arr = value.split(',');
                    //for(var i =0;i<arr.length;i++){
                    //    if($(this).val()==arr[i]){
                    //        $(this).attr('checked',true);
                    //        break;
                    //    }
                    //}TODO
                }else{
                    $(this).val(value);
                }
            }else if(tagName=='SELECT' || tagName=='TEXTAREA'){
                $(this).val(value);
            }
        });
    }
}

///**
// * linkbutton方法扩展 官方修复disable可以点击的bug
// * @param {Object} jq
// */
//$.extend($.fn.linkbutton.methods, {
//    /**
//     * 激活选项（覆盖重写）
//     * @param {Object} jq
//     */
//    enable: function(jq){
//        return jq.each(function(){
//            console.log(this);
//
//            var state = $.data(this, 'linkbutton');
//            if ($(this).hasClass('l-btn-disabled')) {
//                var itemData = state._eventsStore;
//                //恢复超链接
//                if (itemData.href) {
//                    $(this).attr("href", itemData.href);
//                }
//                //回复点击事件
//                if (itemData.onclicks) {
//                    for (var j = 0; j < itemData.onclicks.length; j++) {
//                        $(this).bind('click', itemData.onclicks[j]);
//                    }
//                }
//                //设置target为null，清空存储的事件处理程序
//                itemData.target = null;
//                itemData.onclicks = [];
//                $(this).removeClass('l-btn-disabled');
//            }
//        });
//    },
//    /**
//     * 禁用选项（覆盖重写）
//     * @param {Object} jq
//     */
//    disable: function(jq){
//        return jq.each(function(){
//            var state = $.data(this, 'linkbutton');
//            if (!state._eventsStore)
//                state._eventsStore = {};
//            if (!$(this).hasClass('l-btn-disabled')) {
//                var eventsStore = {};
//                eventsStore.target = this;
//                eventsStore.onclicks = [];
//                //处理超链接
//                var strHref = $(this).attr("href");
//                if (strHref) {
//                    eventsStore.href = strHref;
//                    $(this).attr("href", "javascript:void(0)");
//                }
//                //处理直接耦合绑定到onclick属性上的事件
//                var onclickStr = $(this).attr("onclick");
//                if (onclickStr && onclickStr != "") {
//                    eventsStore.onclicks[eventsStore.onclicks.length] = new Function(onclickStr);
//                    $(this).attr("onclick", "");
//                }
//                //处理使用jquery绑定的事件
//                var eventDatas = $(this).data("events") || $._data(this, 'events');
//                if (eventDatas["click"]) {
//                    var eventData = eventDatas["click"];
//                    for (var i = 0; i < eventData.length; i++) {
//                        if (eventData[i].namespace != "menu") {
//                            eventsStore.onclicks[eventsStore.onclicks.length] = eventData[i]["handler"];
//                            $(this).unbind('click', eventData[i]["handler"]);
//                            i--;
//                        }
//                    }
//                }
//                state._eventsStore = eventsStore;
//                $(this).addClass('l-btn-disabled');
//            }
//        });
//    }
//});